package sse

import (
	"encoding/json"
	"time"

	"github.com/google/uuid"
)

// ResponseStatus 响应状态枚举
type ResponseStatus string

const (
	StatusConnecting    ResponseStatus = "connecting"     // 连接中
	StatusThinking      ResponseStatus = "thinking"       // 思考中
	StatusStreaming     ResponseStatus = "streaming"      // 流式输出中
	StatusToolCalling   ResponseStatus = "tool_calling"   // 工具调用中
	StatusToolCompleted ResponseStatus = "tool_completed" // 工具调用完成
	StatusCompleted     ResponseStatus = "completed"      // 完成
	StatusError         ResponseStatus = "error"          // 错误
)

// ErrorInfo 错误信息
type ErrorInfo struct {
	Code    string `json:"code"`              // 错误代码
	Message string `json:"message"`           // 错误信息
	Details string `json:"details,omitempty"` // 详细信息
	Retry   bool   `json:"retry"`             // 是否可重试
}

// ChatResponse 统一的聊天响应格式（agent层使用）
type ChatResponse struct {
	// 基本信息
	ConversationID uuid.UUID `json:"conversation_id"` // 对话ID
	Timestamp      int64     `json:"timestamp"`       // 时间戳

	// 内容信息
	Content               string `json:"content,omitempty"`                 // 消息内容
	ReasoningContent      string `json:"reasoning_content,omitempty"`       // 推理过程
	DeltaContent          string `json:"delta_content,omitempty"`           // 增量内容(流式)
	DeltaReasoningContent string `json:"delta_reasoning_content,omitempty"` // 增量推理内容(流式)

	// 状态信息
	Status        ResponseStatus `json:"status"`                   // 当前状态
	StatusMessage string         `json:"status_message,omitempty"` // 状态描述

	// 错误信息
	Error *ErrorInfo `json:"error,omitempty"` // 错误详情
}

// NewChatResponse 创建新的聊天响应
func NewChatResponse(conversationID uuid.UUID, status ResponseStatus) *ChatResponse {
	return &ChatResponse{
		ConversationID: conversationID,
		Timestamp:      time.Now().UnixMilli(),
		Status:         status,
	}
}

// WithContent 设置内容
func (r *ChatResponse) WithContent(content string) *ChatResponse {
	r.Content = content
	return r
}

// WithDeltaContent 设置增量内容(流式)
func (r *ChatResponse) WithDeltaContent(deltaContent string) *ChatResponse {
	r.DeltaContent = deltaContent
	return r
}

// WithDeltaReasoningContent 设置增量推理内容(流式)
func (r *ChatResponse) WithDeltaReasoningContent(deltaReasoningContent string) *ChatResponse {
	r.DeltaReasoningContent = deltaReasoningContent
	return r
}

// WithStatusMessage 设置状态描述
func (r *ChatResponse) WithStatusMessage(message string) *ChatResponse {
	r.StatusMessage = message
	return r
}

// WithError 设置错误信息
func (r *ChatResponse) WithError(code, message, details string, retry bool) *ChatResponse {
	r.Status = StatusError
	r.Error = &ErrorInfo{
		Code:    code,
		Message: message,
		Details: details,
		Retry:   retry,
	}
	return r
}

// ToJSON 转换为JSON字符串
func (r *ChatResponse) ToJSON() (string, error) {
	data, err := json.Marshal(r)
	if err != nil {
		return "", err
	}
	return string(data), nil
}

// ToSSEData 转换为SSE格式的数据
func (r *ChatResponse) ToSSEData() (string, error) {
	json, err := r.ToJSON()
	if err != nil {
		return "", err
	}
	return "data: " + json + "\n\n", nil
}
